/**
 * 
 */
package com.redside.webapp.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.redside.model.Business;
import com.redside.model.lookup.BusinessCatLkp;
import com.redside.model.lookup.CountyLkp;
import com.redside.model.lookup.StateLkp;
import com.redside.service.GenericManager;
import com.redside.service.OptionsBeanLookupManager;
import com.redside.webapp.util.CustomBusinessCategoryEditor;
import com.redside.webapp.util.CustomCountyEditor;
import com.redside.webapp.util.CustomStateEditor;

/**
 * @author <a href="mailto:pchapman@easystreet.net">Peter Chapman</a>
 *
 */
public class BusinessFormController extends BaseFormController {
    private GenericManager<Business, Long> businessManager = null;
    private OptionsBeanLookupManager optionsBeanManager;

    public void setBusinessManager(GenericManager<Business, Long> businessManager) {
        this.businessManager = businessManager;
    }
    
    public void setOptionsBeanManager(OptionsBeanLookupManager optionsBeanManager) {
        this.optionsBeanManager = optionsBeanManager;
    }

    public BusinessFormController() {
        setCommandClass(Business.class);
        setCommandName("business");
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            return businessManager.get(new Long(id));
        }
        
        return new Business();
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        logger.debug("entering 'onSubmit' method...");

        Business business = (Business) command;
        boolean isNew = (business.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();
        
        if (request.getParameter("delete") != null) {
            businessManager.remove(business.getId());
            saveMessage(request, getText("business.deleted", locale));
        } else {
            businessManager.save(business);
            String key = (isNew) ? "business.added" : "business.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                success = "redirect:businessform.html?id=" + business.getId();
            }
        }

        return new ModelAndView(success);
    }
    
    /**
     * Set up a custom property editor for converting Longs
     */
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        // convert java.util.Date
        SimpleDateFormat dateFormat = new SimpleDateFormat(getText("date.format"));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat,
                true));

        // convert java.lang.Long
        binder.registerCustomEditor(Long.class, null, new CustomNumberEditor(Long.class,
                null, true));
        
        binder.registerCustomEditor(CountyLkp.class, new CustomCountyEditor(optionsBeanManager));
        
        binder.registerCustomEditor(StateLkp.class, new CustomStateEditor(optionsBeanManager));
        
        binder.registerCustomEditor(BusinessCatLkp.class, new CustomBusinessCategoryEditor(optionsBeanManager));

    }
    
    /**
     * Convenience method for getting a i18n key's value. Calling
     * getMessageSourceAccessor() is used because the RequestContext variable is
     * not set in unit tests b/c there's no DispatchServlet Request.
     * 
     * @param msgKey
     *            the i18n key to lookup
     * @return the message for the key
     */
    public String getText(String msgKey) {
        return getMessageSourceAccessor().getMessage(msgKey);
    }

    /**
     * Convenient method for getting a i18n key's value with a single string
     * argument.
     * 
     * @param msgKey
     *            the i18n key to lookup
     * @param arg
     *            arguments to substitute into key's value
     * @return the message for the key
     */
    public String getText(String msgKey, String arg) {
        return getText(msgKey, new Object[] { arg });
    }

    /**
     * Convenience method for getting a i18n key's value with arguments.
     * 
     * @param msgKey
     *            the i18n key to lookup
     * @param args
     *            arguments to substitute into key's value
     * @return the message for the key
     */
    public String getText(String msgKey, Object[] args) {
        return getMessageSourceAccessor().getMessage(msgKey, args);
    }
}